package nongchang.kuaijiecaifu.com.ncapp_android.ui.fragment.basketmultipledetailfragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import nongchang.kuaijiecaifu.com.ncapp_android.R;
import nongchang.kuaijiecaifu.com.ncapp_android.common.fragment.BaseFragment;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.data.ChildCartManager;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.data.MultipleChildCartManager;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.event.MutipleMoneyEvent;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.BasketCart;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.HomeItemCart;
import nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter.BasketMultipleCartAdapter;
import nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter.basketadapter.BasketCartAdapter;
import nongchang.kuaijiecaifu.com.ncapp_android.util.RxBus;

/**
 * Created by Administrator on 2016/3/11 0011.
 */
public class BasketGoodMultipleDetailFragment extends BaseFragment {
    @BindView(R.id.list)
    RecyclerView list3;
    private BasketMultipleCartAdapter cartAdapter;
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    private MutipleMoneyEvent event;
    private RecyclerView.AdapterDataObserver sumObserver = new RecyclerView.AdapterDataObserver() {

        @Override
        public void onChanged() {
            super.onChanged();
            addSum();
        }
    };

    private void addSum() {
        //执行相应的操作
        float sum = 0;
        for (int i = 0; i < MultipleChildCartManager.cartList.size(); i++) {
            sum += MultipleChildCartManager.cartList.get(i).total_money;
        }
        event.money = sum;
        RxBus.post(event);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_basket_good_multiple_detail, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, getView());
        screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        event = new MutipleMoneyEvent();
        setThirdListView();
    }

    private void setThirdListView() {
        cartAdapter = new BasketMultipleCartAdapter(getContext());
        list3.setAdapter(cartAdapter);
        cartAdapter.registerAdapterDataObserver(sumObserver);
        setCartListener();
        loadCart();
    }

    private void loadCart() {
        cartAdapter.update(MultipleChildCartManager.cartList);
        addSum();
    }

    private void setCartListener() {
        cartAdapter.setOnAddNum(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    int num = MultipleChildCartManager.cartList.get(position).num;
                    num++;
                    MultipleChildCartManager.cartList.get(position).num = num; //修改集合中商品数量
                    MultipleChildCartManager.cartList.get(position).total_money = (MultipleChildCartManager.cartList.get(position).one_price * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    cartAdapter.update(MultipleChildCartManager.cartList);
                }
            }
        });
        cartAdapter.setOnSubNum(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    int num = MultipleChildCartManager.cartList.get(position).num;
                    if (num <= 0) {
                        return;
                    }
                    num--;
                    MultipleChildCartManager.cartList.get(position).num = num; //修改集合中商品数量
                    MultipleChildCartManager.cartList.get(position).total_money = (MultipleChildCartManager.cartList.get(position).one_price * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    cartAdapter.update(MultipleChildCartManager.cartList);
                }
            }
        });
        cartAdapter.setOnTotalNum(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Object tag = v.getTag();
                    ((EditText) v).addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            if (list3.isComputingLayout()) {
                                return;
                            }
//                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                                boolean isOpen = imm.isActive();
                            if (s.toString().equals("")) {
                                ((EditText) v).setText("0");
                                if (tag != null && tag instanceof Integer) {
                                    int position = (Integer) tag;
                                    MultipleChildCartManager.cartList.get(position).num = 1;
                                    MultipleChildCartManager.cartList.get(position).total_money = (MultipleChildCartManager.cartList.get(position).one_price * 1);
                                }
                            } else {
                                if (tag != null && tag instanceof Integer) {
                                    int position = (Integer) tag;
                                    MultipleChildCartManager.cartList.get(position).num = Integer.parseInt(((EditText) v).getText().toString());
                                    MultipleChildCartManager.cartList.get(position).total_money = (MultipleChildCartManager.cartList.get(position).one_price * MultipleChildCartManager.cartList.get(position).num);
                                }
                            }
                        }
                    });
                } else {
                    if (list3.isComputingLayout()) {
                        return;
                    }
                    cartAdapter.update(MultipleChildCartManager.cartList);
                }
            }
        }, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //do something;
                    list3.requestFocus();
                    InputMethodManager imm = (InputMethodManager)
                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        event = null;
    }
}
